package com.TeaManage.servlet;

import com.TeaManage.bean.Logistics;
import com.TeaManage.bean.Order;
import com.TeaManage.bean.OrderItem;
import com.TeaManage.bean.Warehouse;
import com.TeaManage.bean.Inventory;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet(name = "LogisticsServlet", urlPatterns = "/LogisticsServlet")
public class LogisticsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            // 添加物流信息
            String orderIdStr = request.getParameter("order_id");
            String logisticsNo = request.getParameter("logistics_no");
            String logisticsCompany = request.getParameter("logistics_company");
            String shippingTimeStr = request.getParameter("shipping_time");
            String statusStr = request.getParameter("status");
            
            // 验证必填字段
            if (orderIdStr == null || orderIdStr.trim().isEmpty() ||
                logisticsNo == null || logisticsNo.trim().isEmpty() ||
                logisticsCompany == null || logisticsCompany.trim().isEmpty()) {
                request.setAttribute("error", "订单、物流单号和物流公司不能为空");
                loadOrdersForAdd(request);
                request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
                return;
            }
            
            try {
                int orderId = Integer.parseInt(orderIdStr);
                
                // 检查订单是否存在且状态为已支付
                String checkOrderSql = "SELECT status FROM `orders` WHERE order_id = ?";
                List<Logistics> orderStatus = GokJDBCUtil.queryAll(checkOrderSql,Logistics.class, orderId);
                if (orderStatus.isEmpty()) {
                    request.setAttribute("error", "订单不存在");
                    loadOrdersForAdd(request);
                    request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
                    return;
                }
                
                // 检查物流单号是否已存在
                String checkSql = "SELECT COUNT(*) FROM logistics WHERE logistics_no = ?";
                int count = GokJDBCUtil.queryForCount(checkSql, logisticsNo);
                if (count > 0) {
                    request.setAttribute("error", "物流单号已存在");
                    loadOrdersForAdd(request);
                    request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
                    return;
                }
                
                Date shippingTime = null;
                if (shippingTimeStr != null && !shippingTimeStr.trim().isEmpty()) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    shippingTime = sdf.parse(shippingTimeStr);
                }
                
                int status = statusStr != null ? Integer.parseInt(statusStr) : 0;
                
                String sql = "INSERT INTO logistics(order_id, logistics_no, logistics_company, shipping_time, status) VALUES(?, ?, ?, ?, ?)";
                int result = GokJDBCUtil.update(sql, orderId, logisticsNo, logisticsCompany, shippingTime, status);
                
                if (result > 0) {
                    // 更新订单状态为已发货
                    String updateOrderSql = "UPDATE `orders` SET status = 2 WHERE order_id = ?";
                    GokJDBCUtil.update(updateOrderSql, orderId);
                    response.sendRedirect("LogisticsServlet");
                }
                
            } catch (NumberFormatException | ParseException e) {
                request.setAttribute("error", "数据格式不正确");
                loadOrdersForAdd(request);
                request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
            }
            
        } else if ("toAdd".equals(action)) {
            // 跳转到新增页面
            loadOrdersForAdd(request);
            request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);

        } else if ("toShip".equals(action)) {
            // 跳转到发货页面
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr != null && !orderIdStr.trim().isEmpty()) {
                int orderId = Integer.parseInt(orderIdStr);

                // 获取订单信息
                String orderSql = "SELECT o.*, c.customer_name FROM `orders` o LEFT JOIN customer c ON o.customer_id = c.customer_id WHERE o.order_id = ?";
                Order order = GokJDBCUtil.queryForObject(orderSql, Order.class, orderId);

                // 获取订单项信息
                String orderItemsSql = "SELECT oi.*, t.tea_name, t.unit FROM order_item oi LEFT JOIN tea t ON oi.tea_id = t.tea_id WHERE oi.order_id = ?";
                List<OrderItem> orderItems = GokJDBCUtil.queryAll(orderItemsSql, OrderItem.class, orderId);

                // 获取所有仓库
                String warehouseSql = "SELECT * FROM warehouse WHERE status = 1 ORDER BY warehouse_name";
                List<Warehouse> warehouses = GokJDBCUtil.queryAll(warehouseSql, Warehouse.class);

                // 生成物流单号
                String logisticsNo = generateLogisticsNo();

                request.setAttribute("order", order);
                request.setAttribute("orderItems", orderItems);
                request.setAttribute("warehouses", warehouses);
                request.setAttribute("logisticsNo", logisticsNo);
                request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
            } else {
                response.sendRedirect("OrderServlet");
            }

        } else if ("ship".equals(action)) {
            // 处理发货
            String orderIdStr = request.getParameter("order_id");
            String warehouseIdStr = request.getParameter("warehouse_id");
            String logisticsNo = request.getParameter("logistics_no");
            String logisticsCompany = request.getParameter("logistics_company");
            String shippingTimeStr = request.getParameter("shipping_time");
            String statusStr = request.getParameter("status");

            System.out.println("=== 发货请求参数 ===");
            System.out.println("订单ID: " + orderIdStr);
            System.out.println("仓库ID: " + warehouseIdStr);
            System.out.println("物流单号: " + logisticsNo);
            System.out.println("物流公司: " + logisticsCompany);
            System.out.println("发货时间: " + shippingTimeStr);
            System.out.println("状态: " + statusStr);

            // 验证必填字段
            if (orderIdStr == null || orderIdStr.trim().isEmpty() ||
                warehouseIdStr == null || warehouseIdStr.trim().isEmpty() ||
                logisticsNo == null || logisticsNo.trim().isEmpty() ||
                logisticsCompany == null || logisticsCompany.trim().isEmpty()) {
                System.out.println("参数验证失败 - 必填字段为空");
                request.setAttribute("error", "订单、仓库、物流单号和物流公司不能为空");
                // 重新加载数据
                int orderId = Integer.parseInt(orderIdStr);
                loadShipData(request, orderId);
                request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
                return;
            }

            try {
                int orderId = Integer.parseInt(orderIdStr);
                int warehouseId = Integer.parseInt(warehouseIdStr);

                // 检查库存是否充足
                String inventoryCheckResult = checkInventoryWithDetails(orderId, warehouseId);
                if (inventoryCheckResult != null) {
                    request.setAttribute("error", inventoryCheckResult);
                    loadShipData(request, orderId);
                    request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
                    return;
                }

                // 检查物流单号是否已存在
                String checkSql = "SELECT COUNT(*) FROM logistics WHERE logistics_no = ?";
                int count = GokJDBCUtil.queryForCount(checkSql, logisticsNo);
                if (count > 0) {
                    request.setAttribute("error", "物流单号已存在");
                    loadShipData(request, orderId);
                    request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
                    return;
                }

                Date shippingTime = null;
                if (shippingTimeStr != null && !shippingTimeStr.trim().isEmpty()) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
                    shippingTime = sdf.parse(shippingTimeStr);
                } else {
                    shippingTime = new Date();
                }

                int status = statusStr != null ? Integer.parseInt(statusStr) : 0;

                // 开始事务处理
                // 1. 创建物流记录
                String insertLogisticsSql = "INSERT INTO logistics(order_id, logistics_no, logistics_company, shipping_time, status) VALUES(?, ?, ?, ?, ?)";
                int result = GokJDBCUtil.update(insertLogisticsSql, orderId, logisticsNo, logisticsCompany, shippingTime, status);

                if (result > 0) {
                    // 2. 更新订单状态为已发货
                    String updateOrderSql = "UPDATE `orders` SET status = 2 WHERE order_id = ?";
                    GokJDBCUtil.update(updateOrderSql, orderId);

                    // 3. 减少仓库库存
                    updateWarehouseInventory(orderId, warehouseId);

                    response.sendRedirect("LogisticsServlet");
                } else {
                    request.setAttribute("error", "发货失败，请重试");
                    loadShipData(request, orderId);
                    request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
                }

            } catch (NumberFormatException | ParseException e) {
                request.setAttribute("error", "数据格式不正确");
                int orderId = Integer.parseInt(orderIdStr);
                loadShipData(request, orderId);
                request.getRequestDispatcher("/views/logistics/addLogistics.jsp").forward(request, response);
            }

        } else if ("getInventory".equals(action)) {
            // 获取仓库库存信息（AJAX请求）
            response.setContentType("application/json;charset=utf-8");
            String warehouseIdStr = request.getParameter("warehouseId");

            try {
                int warehouseId = Integer.parseInt(warehouseIdStr);

                // 分别查询库存和茶叶信息
                String inventorySql = "SELECT * FROM tea_inventory WHERE warehouse_id = ?";
                List<Inventory> inventoryList = GokJDBCUtil.queryAll(inventorySql, Inventory.class, warehouseId);

                // 构建JSON响应
                StringBuilder json = new StringBuilder();
                json.append("{\"success\": true, \"inventory\": [");
                for (int i = 0; i < inventoryList.size(); i++) {
                    Inventory inv = inventoryList.get(i);

                    // 获取茶叶名称
                    String teaNameSql = "SELECT tea_name FROM tea WHERE tea_id = ?";
                    String teaName = "";
                    try {
                        Object result = GokJDBCUtil.queryForObject(teaNameSql, Object.class, inv.getTea_id());
                        if (result != null) {
                            teaName = result.toString();
                        }
                    } catch (Exception e) {
                        teaName = "未知茶叶";
                    }

                    if (i > 0) json.append(",");
                    json.append("{\"tea_id\": ").append(inv.getTea_id())
                        .append(", \"tea_name\": \"").append(teaName)
                        .append("\", \"quantity\": ").append(inv.getQuantity()).append("}");
                }
                json.append("]}");

                response.getWriter().write(json.toString());
                return;

            } catch (NumberFormatException e) {
                response.getWriter().write("{\"success\": false, \"message\": \"参数错误\"}");
                return;
            }
            
        } else if ("deleteById".equals(action)) {
            // 删除物流信息
            int id = Integer.parseInt(request.getParameter("id"));
            
            // 获取物流信息
            String getLogisticsSql = "SELECT order_id FROM logistics WHERE logistics_id = ?";
            Logistics logistics = GokJDBCUtil.queryForObject(getLogisticsSql, Logistics.class, id);
            
            String sql = "DELETE FROM logistics WHERE logistics_id = ?";
            int result = GokJDBCUtil.update(sql, id);
            
            if (result > 0 && logistics != null) {
                // 将订单状态改回已支付
                String updateOrderSql = "UPDATE `orders` SET status = 1 WHERE order_id = ?";
                GokJDBCUtil.update(updateOrderSql, logistics.getOrder_id());
            }
            
            response.sendRedirect("LogisticsServlet");
            
        } else if ("findById".equals(action)) {
            // 查找物流信息用于编辑
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "SELECT l.*, o.order_no FROM logistics l LEFT JOIN `orders` o ON l.order_id = o.order_id WHERE l.logistics_id = ?";
            Logistics logistics = GokJDBCUtil.queryForObject(sql, Logistics.class, id);
            request.setAttribute("logistics", logistics);
            request.getRequestDispatcher("/views/logistics/editLogistics.jsp").forward(request, response);
            
        } else if ("update".equals(action)) {
            // 更新物流信息
            int id = Integer.parseInt(request.getParameter("logistics_id"));
            String logisticsNo = request.getParameter("logistics_no");
            String logisticsCompany = request.getParameter("logistics_company");
            String shippingTimeStr = request.getParameter("shipping_time");
            String receiverTimeStr = request.getParameter("receiver_time");
            String statusStr = request.getParameter("status");
            
            // 验证必填字段
            if (logisticsNo == null || logisticsNo.trim().isEmpty() ||
                logisticsCompany == null || logisticsCompany.trim().isEmpty()) {
                request.setAttribute("error", "物流单号和物流公司不能为空");
                Logistics logistics = GokJDBCUtil.queryForObject("SELECT l.*, o.order_no FROM logistics l LEFT JOIN `orders` o ON l.order_id = o.order_id WHERE l.logistics_id = ?", Logistics.class, id);
                request.setAttribute("logistics", logistics);
                request.getRequestDispatcher("/views/logistics/editLogistics.jsp").forward(request, response);
                return;
            }
            
            try {
                // 检查物流单号是否已存在（排除当前记录）
                String checkSql = "SELECT COUNT(*) FROM logistics WHERE logistics_no = ? AND logistics_id != ?";
                int count = GokJDBCUtil.queryForCount(checkSql, logisticsNo, id);
                if (count > 0) {
                    request.setAttribute("error", "物流单号已存在");
                    Logistics logistics = GokJDBCUtil.queryForObject("SELECT l.*, o.order_no FROM logistics l LEFT JOIN `orders` o ON l.order_id = o.order_id WHERE l.logistics_id = ?", Logistics.class, id);
                    request.setAttribute("logistics", logistics);
                    request.getRequestDispatcher("/views/logistics/editLogistics.jsp").forward(request, response);
                    return;
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

                Timestamp shippingTime = new Timestamp(System.currentTimeMillis());
                Timestamp receiverTime = null;
                if (shippingTimeStr != null && !shippingTimeStr.trim().isEmpty()) {
                    Date utilDate = sdf.parse(shippingTimeStr);
                    shippingTime = new Timestamp(utilDate.getTime());

                }
                if (receiverTimeStr != null && !receiverTimeStr.trim().isEmpty()) {
                    Date utilDate = sdf.parse(receiverTimeStr);
                    receiverTime = new Timestamp(utilDate.getTime());
                }
                
                int status = statusStr != null ? Integer.parseInt(statusStr) : 0;
                
                String sql = "UPDATE logistics SET logistics_no = ?, logistics_company = ?, shipping_time = ?, receiver_time = ?, status = ? WHERE logistics_id = ?";
                int result = GokJDBCUtil.update(sql, logisticsNo, logisticsCompany, shippingTime, receiverTime, status, id);
                
                if (result > 0) {
                    response.sendRedirect("LogisticsServlet");
                }
                
            } catch (NumberFormatException | ParseException e) {
                request.setAttribute("error", "数据格式不正确");
                Logistics logistics = GokJDBCUtil.queryForObject("SELECT l.*, o.order_no FROM logistics l LEFT JOIN `orders` o ON l.order_id = o.order_id WHERE l.logistics_id = ?", Logistics.class, id);
                request.setAttribute("logistics", logistics);
                request.getRequestDispatcher("/views/logistics/editLogistics.jsp").forward(request, response);
            }
            
        } else if ("search".equals(action)) {
            // 搜索物流信息
            String logisticsNo = request.getParameter("logisticsNo");
            String logisticsCompany = request.getParameter("logisticsCompany");
            String orderNo = request.getParameter("orderNo");
            String statusStr = request.getParameter("status");
            
            // 分页参数
            int page = 1;
            int pageSize = 10;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 10;
            }
            
            // 构建动态 SQL 和参数列表
            StringBuilder sql = new StringBuilder("SELECT l.*, o.order_no, c.customer_name FROM logistics l LEFT JOIN `orders` o ON l.order_id = o.order_id LEFT JOIN customer c ON o.customer_id = c.customer_id WHERE 1=1");
            List<Object> params = new ArrayList<>();
            
            if (logisticsNo != null && !logisticsNo.trim().isEmpty()) {
                sql.append(" AND l.logistics_no LIKE ?");
                params.add("%" + logisticsNo + "%");
            }
            if (logisticsCompany != null && !logisticsCompany.trim().isEmpty()) {
                sql.append(" AND l.logistics_company LIKE ?");
                params.add("%" + logisticsCompany + "%");
            }
            if (orderNo != null && !orderNo.trim().isEmpty()) {
                sql.append(" AND o.order_no LIKE ?");
                params.add("%" + orderNo + "%");
            }
            if (statusStr != null && !statusStr.trim().isEmpty()) {
                sql.append(" AND l.status = ?");
                params.add(Integer.parseInt(statusStr));
            }
            
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") AS total";
            int total = GokJDBCUtil.queryForCount(countSql, params.toArray());
            
            // 添加分页
            sql.append(" ORDER BY l.logistics_id DESC LIMIT ?, ?");
            params.add((page - 1) * pageSize);
            params.add(pageSize);
            
            List<Logistics> logisticsList = GokJDBCUtil.queryAll(sql.toString(), Logistics.class, params.toArray());
            
            // 计算总页数
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            
            // 返回结果
            request.setAttribute("logisticsList", logisticsList);
            request.setAttribute("logisticsNo", logisticsNo);
            request.setAttribute("logisticsCompany", logisticsCompany);
            request.setAttribute("orderNo", orderNo);
            request.setAttribute("status", statusStr);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/logistics/logistics.jsp").forward(request, response);
            
        } else {
            // 默认显示物流列表
            loadLogisticsList(request, response);
        }
    }
    
    private void loadLogisticsList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数
        int page = 1;
        int pageSize = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            page = 1;
            pageSize = 10;
        }
        
        // 查询总数
        String countSql = "SELECT COUNT(*) FROM logistics";
        int total = GokJDBCUtil.queryForCount(countSql);
        
        // 查询数据
        String sql = "SELECT l.*, o.order_no, c.customer_name FROM logistics l LEFT JOIN `orders` o ON l.order_id = o.order_id LEFT JOIN customer c ON o.customer_id = c.customer_id ORDER BY l.logistics_id DESC LIMIT ?, ?";
        List<Logistics> logisticsList = GokJDBCUtil.queryAll(sql, Logistics.class, (page-1)*pageSize, pageSize);
        
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        
        request.setAttribute("logisticsList", logisticsList);
        request.setAttribute("page", page);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("views/logistics/logistics.jsp").forward(request, response);
    }
    
    private void loadOrdersForAdd(HttpServletRequest request) {
        // 获取已支付但未发货的订单
        String orderSql = "SELECT o.*, c.customer_name FROM `orders` o LEFT JOIN customer c ON o.customer_id = c.customer_id WHERE o.status = 1 AND o.order_id NOT IN (SELECT order_id FROM logistics)";
        List<Order> orderList = GokJDBCUtil.queryAll(orderSql, Order.class);
        request.setAttribute("orderList", orderList);
    }

    private String generateLogisticsNo() {
        // 生成物流单号：WL + 时间戳 + 随机数
        long timestamp = System.currentTimeMillis();
        int random = (int)(Math.random() * 1000);
        return "WL" + timestamp + String.format("%03d", random);
    }

    private void loadShipData(HttpServletRequest request, int orderId) {
        // 获取订单信息
        String orderSql = "SELECT o.*, c.customer_name FROM `orders` o LEFT JOIN customer c ON o.customer_id = c.customer_id WHERE o.order_id = ?";
        Order order = GokJDBCUtil.queryForObject(orderSql, Order.class, orderId);

        // 获取订单项信息
        String orderItemsSql = "SELECT oi.*, t.tea_name, t.unit FROM order_item oi LEFT JOIN tea t ON oi.tea_id = t.tea_id WHERE oi.order_id = ?";
        List<OrderItem> orderItems = GokJDBCUtil.queryAll(orderItemsSql, OrderItem.class, orderId);

        // 获取所有仓库
        String warehouseSql = "SELECT * FROM warehouse WHERE status = 1 ORDER BY warehouse_name";
        List<Warehouse> warehouses = GokJDBCUtil.queryAll(warehouseSql, Warehouse.class);

        // 生成物流单号
        String logisticsNo = generateLogisticsNo();

        request.setAttribute("order", order);
        request.setAttribute("orderItems", orderItems);
        request.setAttribute("warehouses", warehouses);
        request.setAttribute("logisticsNo", logisticsNo);
    }

    private boolean checkInventorySufficient(int orderId, int warehouseId) {
        // 获取订单项
        String orderItemsSql = "SELECT * FROM order_item WHERE order_id = ?";
        List<OrderItem> orderItems = GokJDBCUtil.queryAll(orderItemsSql, OrderItem.class, orderId);

        System.out.println("=== 库存检查开始 ===");
        System.out.println("订单ID: " + orderId + ", 仓库ID: " + warehouseId);
        System.out.println("订单项数量: " + (orderItems != null ? orderItems.size() : 0));

        for (OrderItem item : orderItems) {
            System.out.println("检查商品 - 茶叶ID: " + item.getTea_id() + ", 需要数量: " + item.getQuantity());

            // 检查每个商品的库存
            String inventorySql = "SELECT quantity FROM tea_inventory WHERE tea_id = ? AND warehouse_id = ?";
            try {
                Object result = GokJDBCUtil.queryForObject(inventorySql, Object.class, item.getTea_id(), warehouseId);
                double currentStock = 0.0;
                if (result != null) {
                    if (result instanceof Number) {
                        currentStock = ((Number) result).doubleValue();
                    } else {
                        try {
                            currentStock = Double.parseDouble(result.toString());
                        } catch (NumberFormatException e) {
                            System.out.println("无法解析库存数量: " + result + " (类型: " + result.getClass().getSimpleName() + ")");
                            currentStock = 0.0;
                        }
                    }
                }

                System.out.println("库存查询结果 - 茶叶ID: " + item.getTea_id() + ", 当前库存: " + currentStock + ", 需要数量: " + item.getQuantity());

                if (currentStock < item.getQuantity()) {
                    System.out.println("库存不足 - 茶叶ID: " + item.getTea_id() + ", 当前库存: " + currentStock + " < 需要数量: " + item.getQuantity());
                    return false; // 库存不足
                }
            } catch (Exception e) {
                System.out.println("库存查询异常 - 茶叶ID: " + item.getTea_id() + ", 异常: " + e.getMessage());
                e.printStackTrace();
                return false; // 查询失败，认为库存不足
            }
        }
        System.out.println("=== 库存检查通过 ===");
        return true; // 所有商品库存充足
    }

    private String checkInventoryWithDetails(int orderId, int warehouseId) {
        System.out.println("=== 详细库存检查开始 ===");
        System.out.println("订单ID: " + orderId + ", 仓库ID: " + warehouseId);

        try {
            // 使用原生JDBC查询，避免GokJDBCUtil的类型转换问题
            Connection conn = GokJDBCUtil.getConnection();

            // 获取订单项
            String orderItemsSql = "SELECT * FROM order_item WHERE order_id = ?";
            PreparedStatement orderStmt = conn.prepareStatement(orderItemsSql);
            orderStmt.setInt(1, orderId);
            ResultSet orderRs = orderStmt.executeQuery();

            boolean hasItems = false;
            while (orderRs.next()) {
                hasItems = true;
                int teaId = orderRs.getInt("tea_id");
                double needQuantity = orderRs.getDouble("quantity");

                System.out.println("检查商品 - 茶叶ID: " + teaId + ", 需要数量: " + needQuantity);

                // 获取茶叶名称
                String teaNameSql = "SELECT tea_name FROM tea WHERE tea_id = ?";
                PreparedStatement teaStmt = conn.prepareStatement(teaNameSql);
                teaStmt.setInt(1, teaId);
                ResultSet teaRs = teaStmt.executeQuery();

                String teaName = "未知茶叶";
                if (teaRs.next()) {
                    teaName = teaRs.getString("tea_name");
                }
                teaRs.close();
                teaStmt.close();

                // 检查库存
                String inventorySql = "SELECT quantity FROM tea_inventory WHERE tea_id = ? AND warehouse_id = ?";
                PreparedStatement invStmt = conn.prepareStatement(inventorySql);
                invStmt.setInt(1, teaId);
                invStmt.setInt(2, warehouseId);
                ResultSet invRs = invStmt.executeQuery();

                double currentStock = 0.0;
                if (invRs.next()) {
                    currentStock = invRs.getDouble("quantity");
                } else {
                    // 没有库存记录
                    invRs.close();
                    invStmt.close();
                    orderRs.close();
                    orderStmt.close();
                    conn.close();
                    return "商品 [" + teaName + "] 在所选仓库中没有库存记录";
                }
                invRs.close();
                invStmt.close();

                System.out.println("库存查询结果 - 茶叶: " + teaName + " (ID: " + teaId + "), 当前库存: " + currentStock + ", 需要数量: " + needQuantity);

                if (currentStock < needQuantity) {
                    String errorMsg = "商品 [" + teaName + "] 库存不足：当前库存 " + currentStock + "，需要 " + needQuantity;
                    System.out.println("库存不足: " + errorMsg);
                    orderRs.close();
                    orderStmt.close();
                    conn.close();
                    return errorMsg;
                }
            }

            orderRs.close();
            orderStmt.close();
            conn.close();

            if (!hasItems) {
                return "订单中没有商品项";
            }

            System.out.println("=== 详细库存检查通过 ===");
            return null; // 所有商品库存充足

        } catch (Exception e) {
            String errorMsg = "库存检查时发生数据库错误：" + e.getMessage();
            System.out.println("库存检查异常: " + errorMsg);
            e.printStackTrace();
            return errorMsg;
        }
    }

    private void updateWarehouseInventory(int orderId, int warehouseId) {
        // 获取订单项
        String orderItemsSql = "SELECT * FROM order_item WHERE order_id = ?";
        List<OrderItem> orderItems = GokJDBCUtil.queryAll(orderItemsSql, OrderItem.class, orderId);

        for (OrderItem item : orderItems) {
            // 减少库存
            String updateSql = "UPDATE tea_inventory SET quantity = quantity - ? WHERE tea_id = ? AND warehouse_id = ?";
            GokJDBCUtil.update(updateSql, item.getQuantity(), item.getTea_id(), warehouseId);
        }
    }
}
